import wxBaaS from '../sdk-wechat.3.23.5';

// 获取用户ID
const user_id = wx.getStorageSync('userId');

// 收藏药膳
export async function collectCase(case_id) {
  // 确保 case_id 是字符串类型
  const caseIdStr = String(case_id);

  //创建一个指向 CloudBase 数据库中名为 'case_collection' 表格的引用
  const collectionTable = new wxBaaS.TableObject('case_collection');
  let MyRecord = collectionTable.create();
  MyRecord.set({
    user_id: wx.getStorageSync('userId'),
    case_id: caseIdStr
  });

  try {
    await MyRecord.save();
    return {
      code: 0,
      message: "收藏成功"
    };
  } catch (error) {
    wx.showToast({
      title: error.message,
      icon: 'none'
    });
    return Promise.reject(error.message);
  }
}

// 取消收藏药膳
export async function unCollectCase(case_id) {
  try {
    // 先获取id
    const query = new wx.BaaS.Query();
    //添加查询条件
    query.contains("user_id", user_id);
    query.contains("case_id", case_id);
    const response = await new wxBaaS.TableObject('case_collection').setQuery(query).find();
    const objects = response.data.objects;
    if (!objects.length) throw new Error("取消收藏失败");

    // 删除记录
    const record_id = objects[0]._id;
    await new wxBaaS.TableObject('case_collection').delete(record_id);
    return {
      code: 0,
      message: "取消收藏成功"
    };
  } catch (error) {
    wx.showToast({
      title: error.message,
      icon: 'none'
    });
    return Promise.reject(error.message);
  }
}

// 获取所有收藏药膳
export async function getCollectCaseList(userId) {
  if (!userId) {
    wx.showToast({
      title: '用户未登录',
      icon: 'none'
    });
    return Promise.reject('用户未登录');
  }

  try {
    const query = new wx.BaaS.Query();
    query.contains("user_id", userId);
    const response = await new wxBaaS.TableObject('case_collection').setQuery(query).find();

    const objects = response.data.objects;
    //从查询结果中提取所有收藏案例的 ID，存储在 collectedIds 数组中
    const collectedIds = objects.map(item => item.case_id);

    let results = [];
    for (let caseId of collectedIds) {
      try {
        let {
          data
        } = await new wxBaaS.TableObject('Medifood_case').get(caseId);
        results.push(data);
      } catch (error) {
        console.error(`获取药膳ID ${caseId} 失败`, error);
      }
    }

    return {
      code: 0,
      message: "获取成功",
      data: results
    };
  } catch (error) {
    wx.showToast({
      title: error.message,
      icon: 'none'
    });
    return Promise.reject(error.message);
  }
}